<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px">
          <!--      <el-form-item label="健身房id" prop="gymId">
            <el-input v-model="queryParams.gymId" placeholder="请输入健身房id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="MAC地址" prop="deviceSn">
            <el-input v-model="queryParams.deviceSn" placeholder="请输入设备MAC码" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <!--          <el-form-item label="设备令牌" prop="deviceToken">
            <el-input v-model="queryParams.deviceToken" placeholder="请输入设备令牌" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--     <el-form-item label="是否已绑定；0-未绑定；1-已绑定" prop="isBind">
            <el-input v-model="queryParams.isBind" placeholder="请输入是否已绑定；0-未绑定；1-已绑定" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="最近登录时间" prop="loginTime">
            <el-date-picker clearable
              v-model="queryParams.loginTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择最近登录时间了"
            />
          </el-form-item>
          <el-form-item label="离线时间" prop="offLineTime">
            <el-date-picker clearable
              v-model="queryParams.offLineTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择离线时间"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['primary:device:edit']">绑定</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['primary:device:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Refresh" @click="handleUpdateResh"
              v-hasPermi="['primary:device:edit']">重新下发</el-button>
          </el-col>

          <!--          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['primary:device:remove']">删除</el-button>
          </el-col> -->
          <!--          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['primary:device:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="MAC地址" align="center" prop="deviceSn" />
        <el-table-column label="SN" align="center" prop="snCode" />
        <el-table-column label="设备状态" align="center">
          <template #default="scope">
            <dict-tag :options="g_device_status" :value="scope.row.status" />
          </template>
        </el-table-column>

        <el-table-column label="进出场类型" align="center">
          <template #default="scope">
            <dict-tag :options="g_entryexit_type" :value="scope.row.inOutType" />
          </template>
        </el-table-column>
        <el-table-column label="设备类型" align="center" prop="deviceType">
          <template #default="scope">
            <dict-tag :options="g_device_type" :value="scope.row.deviceType" />
          </template>
        </el-table-column>
        <el-table-column label="最近登录时间" align="center" prop="loginTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.loginTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="离线时间" align="center" prop="offLineTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.offLineTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:device:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="一键清空" placement="top">
              <el-button link type="primary" icon="Warning" @click="qingkong(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="解绑" placement="top">
              <el-button link type="primary" icon="CircleClose" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:device:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="开闸" placement="top">
              <el-button link type="primary" icon="Unlock" @click="handlekai(scope.row)"
                v-hasPermi="['primary:device:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="开启相机识别" placement="top">
              <el-button link type="primary" icon="Open" @click="handleCamera(scope.row)"
                v-hasPermi="['primary:device:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="580px" append-to-body>
      <el-form ref="deviceFormRef" :model="form" :rules="rules" label-width="110px">
        <!--        <el-form-item label="健身房id" prop="gymId">
          <el-input v-model="form.gymId" placeholder="请输入健身房id" />
        </el-form-item> -->
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" @input="trimInput('deviceName')" />
        </el-form-item>
        <el-form-item label="MAC地址" prop="deviceSn">
          <el-input v-model="form.deviceSn" placeholder="请输入MAC地址" @input="trimInput('deviceSn')" />
        </el-form-item>
        <el-form-item label="SN" prop="snCode">
          <el-input v-model="form.snCode" placeholder="请输入SN码" @input="trimInput('snCode')" />
        </el-form-item>
        <el-form-item label="进出场类型" align="center" prop="inOutType">
          <el-select v-model="form.inOutType" placeholder="请选择">
            <el-option v-for="dict in g_entryexit_type" :key="dict.value" :label="dict.label"
              :value="Number(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 重新下发~~~~~~~~~~~~~~~~~~~~ -->
    <el-dialog :title="dialogResh.title" v-model="dialogResh.visible" width="1200px" append-to-body>
      <el-form ref="memberFormRef" :model="FormResh" label-width="100px">
        <!--        <el-form-item label="图片" prop="ossId">
              <imageUpload v-model="form.ossId" ref="childValue" :limit="1" :fileSize="1" :rule="1" />
            </el-form-item> -->
        <el-form-item label="设备选择" prop="deviceId">
          <el-select v-model="FormResh.deviceId" placeholder="请选择" filterable multiple>
            <el-option v-for="dict in deviceList" :key="dict.id" :label="dict.deviceName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormResh">确 定</el-button>
          <el-button @click="cancelResh">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 清空人脸 -->
    <el-dialog :title="dialogDanger.title" v-model="dialogDanger.visible" width="1200px" append-to-body>
      <el-form ref="memberFormRef" :model="FormResh" label-width="100px">

        <el-form-item>
          <span style="font-size: 20px;">该操作将删除该人脸设备下，所有已下发的人脸数据，确认删除吗?</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelReshDanger">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitFormDanger">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Device" lang="ts">
  import { listDevice, getDevice, delDevice, addDevice, updateDevice, kaizha, qing, Camera, DevicePushAll } from '@/api/primary/device';
  import { DeviceVO, DeviceQuery, DeviceForm } from '@/api/primary/device/types';
  import { nextTick } from 'vue';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { g_device_type, g_entryexit_type, g_device_status } = toRefs<any>(proxy?.useDict("g_device_type", 'g_entryexit_type', 'g_device_status'));
  const deviceList = ref<DeviceVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const Shebei = ref({
    id: undefined,
    name: undefined,
  });
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const dataoo = reactive({
    isBind: [ //
      { value: 0, label: '未绑定' },
      { value: 1, label: '已绑定' },
    ]
  })
  const dialogResh = reactive<any>({
    visible: false,
    title: ''
  });
  const dialogDanger = reactive<any>({
    visible: false,
    title: ''
  });
  const FormResh = ref<any>({
    deviceId: undefined//
  });
  const queryFormRef = ref<ElFormInstance>();
  const deviceFormRef = ref<ElFormInstance>();

  const dialog = reactive<any>({
    visible: false,
    title: ''
  });

  const initFormData : DeviceForm = {
    id: undefined,
    gymId: undefined,
    deviceName: undefined,
    deviceSn: undefined,
    snCode: undefined,
    deviceToken: undefined,
    status: undefined,
    isBind: undefined,
    inOutType: undefined,
    deviceType: undefined,
    loginTime: undefined,
    offLineTime: undefined,
  }
  const data = reactive<PageData<DeviceForm, DeviceQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      gymId: undefined,
      deviceName: undefined,
      deviceSn: undefined,
      snCode: undefined,
      deviceToken: undefined,
      status: undefined,
      isBind: undefined,
      inOutType: undefined,
      deviceType: undefined,
      loginTime: undefined,
      offLineTime: undefined,
      params: {
      }
    },
    rules: {
      id: [
        { required: true, message: "id不能为空", trigger: "blur" }
      ],
      gymId: [
        { required: true, message: "健身房id不能为空", trigger: "blur" }
      ],
      deviceName: [
        { required: true, message: "设备名称不能为空", trigger: "blur" }
      ],
      deviceSn: [
        { required: true, message: "MAC不能为空", trigger: "blur" }
      ],
      deviceToken: [
        { required: true, message: "设备令牌不能为空", trigger: "blur" }
      ],
      status: [
        { required: true, message: "设备状态；0-离线；1-在线不能为空", trigger: "change" }
      ],
      isBind: [
        { required: true, message: "是否已绑定；0-未绑定；1-已绑定不能为空", trigger: "blur" }
      ],
      inOutType: [
        { required: true, message: "进出场类型不能为空", trigger: "blur" }
      ],
      deviceType: [
        { required: true, message: "设备类型；1-c9不能为空", trigger: "change" }
      ],
      loginTime: [
        { required: true, message: "最近登录时间不能为空", trigger: "blur" }
      ],
      offLineTime: [
        { required: true, message: "离线时间不能为空", trigger: "blur" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询设备列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listDevice(queryParams.value);
    deviceList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }
  const trimInput = (field) => {
    nextTick(() => {
      if (form.value[field]) {
        form.value[field] = form.value[field].trim();
      }
    });
  };
  const cancelResh = () => {
    reset();
    dialogResh.visible = false
  }
  const cancelReshDanger = () => {
    reset();
    dialogDanger.visible = false
  }
  /** 开闸 */
  const handlekai = async (row ?: any) => {
    const _id = row?.id
    const res = await kaizha(_id);
    proxy?.$modal.msgSuccess("开闸成功");
  }
  /** 开启相机识别 */
  const handleCamera = async (row ?: any) => {
    const _id = row?.id
    const res = await Camera(_id);
    proxy?.$modal.msgSuccess("开启成功");
  }
  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    deviceFormRef.value?.resetFields();
  }
  /** 重新下发 */
  const submitFormResh = async () => {
    if (FormResh.value.deviceId.length == 0) {
      proxy?.$modal.msgError("请先选择设备!");
      return
    }
    buttonLoading.value = true;
    await DevicePushAll(FormResh.value).finally(() => buttonLoading.value = false);
    proxy?.$modal.msgSuccess("提交成功,人脸同步中");
    dialogResh.visible = false;
    await getList();
  }
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }
  /** 修改按钮操作 */
  const handleUpdateResh = () => {
    reset();
    dialogResh.visible = true;
    dialogResh.title = "重新下发";
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : DeviceVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加设备";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: DeviceVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getDevice(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改设备";
  }

  /** 清空按钮操作 */
  const qingkong = async (row ?: DeviceVO) => {
    let name = row.deviceName
    await proxy?.$modal.confirm('是否确认清空"' + name + '"该人脸设备下的全部数据？').finally(() => loading.value = false);
    dialogDanger.title = '清空人脸设备'
    dialogDanger.visible = true
    Shebei.value.id = row?.id || ids.value[0]
    Shebei.value.name = row?.deviceName
  }
  /** 清空按钮操作 */
  const submitFormDanger = async () => {
    await qing(Shebei.value.id);
    proxy?.$modal.msgSuccess("清空成功");
    dialogDanger.visible = false
    await getList();
  }

  /** 提交按钮 */
  const submitForm = () => {
    deviceFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateDevice(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          await addDevice(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("绑定成功");
        }

        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 解绑按钮操作 */
  const handleDelete = async (row ?: DeviceVO) => {
    const _ids = row?.id || ids.value;
    let name = row.deviceName
    await proxy?.$modal.confirm('是否确认解绑设备名称为"' + name + '"的数据项？解绑后将不能正常使用').finally(() => loading.value = false);
    await proxy?.$modal.confirm('您已了解解绑后果，确认解绑吗').finally(() => loading.value = false);
    await delDevice(_ids);
    proxy?.$modal.msgSuccess("解绑成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('primary/device/export', {
      ...queryParams.value
    }, `device_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    getList();
  });
</script>